//
//  EareList_ViewController.m
//  CarNetwork_logistics
//
//  Created by 高启 on 15/11/11.
//  Copyright © 2015年 turingEdu. All rights reserved.
//

#import "MultiMpleList_ViewController.h"
#import "EreaListModel.h"

@interface MultiMpleList_ViewController ()

@end

@implementation MultiMpleList_ViewController
{
    UITableView      *_tableViewList;
    NSMutableArray   *currentList;          //当前维护的数据
    NSMutableArray   *wordListArr;          //字母列表
    NSMutableArray   *provinceList;
    NSMutableArray   *cityList;
    UIView           *searchView;
    NSMutableArray   *currentSourceData;    //当前数据的原始数据
    UITextField      *searchText;
    NSMutableArray   *searchArr;            //当前查询的数据
    NSMutableArray   *codeArr;              // 省的code数据
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createWordList];
    [self createTableHeaderView];
    [self createTableView];
    [self dataManager];

    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navtitle.text = self.titleStr;
}
/**
 *  数据处理
 */
- (void)dataManager
{
    EreaListModel  *ereaModel = [EreaListModel sharedManager];
    if ([self.type isEqualToString:@"0"])
    {
        //获取省份的信息
        provinceList = [ereaModel getProvinceList];
        for (NSDictionary *dic in provinceList)
        {
            [searchArr addObject:[dic objectForKey:@"name"]];
            [codeArr addObject:[dic objectForKey:@"code"]];
        }

        currentSourceData = provinceList;
    }else if ([self.type isEqualToString:@"1"])
    {
        cityList = [ereaModel getCityWithProvinceId:self.provinceCode];
        for (NSDictionary *dic in cityList)
        {
            [searchArr addObject:[dic objectForKey:@"name"]];
        }
       
        currentSourceData  = cityList;
    }else if ([self.type isEqualToString:@"3"])
    {
        //危险品
        
    }else
    {
        //易燃品
    }
    
    

  
    
   [self UpdateDataWithBuffer:currentSourceData];
}
//数据更新
-(void)UpdateDataWithBuffer:(NSArray *)buffer
{
    
    //当前子节点
    NSMutableArray       *CellArr = [[NSMutableArray alloc] init];
    //当前子节点字典
    NSMutableDictionary  *dicBuff = [[NSMutableDictionary alloc] init];
    currentList = [[NSMutableArray alloc] init];
    //全部本地数据库信息遍历
    for (NSDictionary *dic in buffer)
    {
        //取得当前排序标题
        
        NSInteger m_OrderByNum = [UtilsHelper ChineseStringFirstLetterConvert:[dic objectForKey:@"name"]];
        NSNumber *num  = [NSNumber numberWithInteger:m_OrderByNum];
        NSString *NowSectionTitle = [NSString stringWithFormat:@"%c",[num charValue]];

        if ([dicBuff objectForKey:SectionTitle] == nil)
        {
            [dicBuff setObject:NowSectionTitle forKey:SectionTitle];
        }
        
        //如果当前子节点字典中的组标题于当前排序字母相同，则向当前字节点数组中加入当前Cell
        if ([[dicBuff objectForKey:SectionTitle] isEqualToString:NowSectionTitle])
        {
            [CellArr addObject:dic];
        }
        else
        {
            //如果不相同，则代表前一个子节点已经录入完成，将当前子节点Dic存储到总Section数组中
            [dicBuff setObject:CellArr forKey:SectionValue];
            [currentList addObject:dicBuff];
            //同时创建新的字节点数组与子节点Dic
            CellArr = [[NSMutableArray alloc] init];
            [CellArr addObject:dic];
            dicBuff = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                       NowSectionTitle,SectionTitle,
                       CellArr,SectionValue,nil];
        }
    }
    [dicBuff setObject:CellArr forKey:SectionValue];
    //循环结束后将最后一组节点Dic加入到总Section数组中
    [currentList addObject:dicBuff];
    [_tableViewList reloadData];
}

/**
 *  创建字母列表
 */
- (void)createWordList
{
    wordListArr = [[NSMutableArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#" ,nil];
   
    
}


- (void)createTableView
{
    _tableViewList = [[UITableView alloc]initWithFrame:CGRectMake(0, searchView.frame.origin.y + searchView.frame.size.height, kUIScreenWidth, kUIScreenHeight-kStateNavHeight-searchView.frame.size.height - searchView.frame.origin.y-64)];
    [_tableViewList setDelegate:self];
    [_tableViewList setDataSource:self];
    [_tableViewList setScrollEnabled:YES];
    [_tableViewList setShowsHorizontalScrollIndicator:NO];
    [_tableViewList setShowsVerticalScrollIndicator:NO];
    [_tableViewList setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    [self.view addSubview:_tableViewList];
}

- (void)createTableHeaderView
{
    searchView = [[UIView alloc]init];
    [searchView setBackgroundColor:[UIColor clearColor]];
    [searchView.layer setMasksToBounds:YES];
    [searchView.layer setBorderColor:[[UIColor HexStrWithColor:@"aaaaaa"] CGColor]];
    [searchView.layer setBorderWidth:1.0];
    [searchView setFrame:CGRectMake(-1, kStateNavHeight, kUIScreenWidth+2, 56)];
 
    [self.view addSubview:searchView];

    searchText = [[UITextField alloc]init];
    [searchText setBackgroundColor:[UIColor clearColor]];
    [searchText addTarget:self action:@selector(searchWithContent:) forControlEvents:UIControlEventValueChanged];
    [searchView addSubview:searchText];
    [searchText mas_makeConstraints:^(MASConstraintMaker *make)
    {
        make.center.equalTo(searchView);
        make.height.equalTo(searchView);
        make.width.equalTo(searchView.mas_width).with.multipliedBy(0.9);
        
        
    }];
    [searchText setDelegate:self];
    [searchText setPlaceholder:@"输入城市名"];
    [searchText setReturnKeyType:UIReturnKeySearch];
    [searchText setKeyboardType:UIKeyboardTypeDefault];
   
    UIImage *searchImage =[UIImage imageNamed:@"fdj"];
    UIImageView *leftImageView = [[UIImageView alloc]initWithImage:searchImage];
    [leftImageView setImage:searchImage];
    [searchText setLeftView:leftImageView];
    [searchText setLeftViewMode:UITextFieldViewModeAlways];
   
}
//添加索引列

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView

{
    
    
    
    if (tableView == self.searchDisplayController.searchResultsTableView)
        
    {
        
        return nil;
        
    }
    
    
    
    return wordListArr;
    
}

//索引列点击事件

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index

{
    NSString *key = [wordListArr objectAtIndex:index];
    if (key == UITableViewIndexSearch)
    {
        [tableView setContentOffset:CGPointZero animated:NO];
        return NSNotFound;
    }
    else
        return index;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return nil;
    }
    UIView *headView = [[UIView alloc]init];
    headView.backgroundColor = [UIColor HexStrWithColor:@"f7f7f7"];
    [headView setFrame:CGRectMake(0, 0, _tableViewList.frame.size.width, [self tableView:tableView heightForHeaderInSection:section])];
    
    //标题文字
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.backgroundColor = [UIColor HexStrWithColor:@"f7f7f7"];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.frame = CGRectMake(15, 7.5, 200, 15);
    NSString *titleStr = [[currentList objectAtIndex:section] objectForKey:SectionTitle];
    titleLabel.text = titleStr;
    [headView addSubview:titleLabel];
    
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 30.f;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[[currentList objectAtIndex:section] objectForKey:SectionValue] count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [currentList count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
       NSString *new_cell_indentifer = @"erea_cell";

  
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:new_cell_indentifer];
        if (!cell)
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:new_cell_indentifer];
            [cell setBackgroundColor:[UIColor whiteColor]];
            
            UILabel *titleLabel = [[UILabel alloc]init];
            [titleLabel setFont:[UIFont systemFontOfSize:16]];
            [titleLabel setTag:102];
            [cell addSubview:titleLabel];
            [titleLabel mas_makeConstraints:^(MASConstraintMaker *make)
            {
                make.centerY.equalTo(cell);
                make.left.equalTo(cell.mas_left).with.offset(20);
                make.width.mas_equalTo(@150);
                make.height.equalTo(cell.mas_height).with.multipliedBy(0.5);
                
            }];
       
        }
    NSDictionary *dic = [[[currentList objectAtIndex:indexPath.section] objectForKey:SectionValue] objectAtIndex:indexPath.row];
    UILabel *titleLabel= (UILabel *)[cell viewWithTag:102];
    [titleLabel setText:[dic objectForKey:@"name"]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSMutableDictionary *userInfo = [[NSMutableDictionary alloc]init];
    if ([self.from isEqualToString:@"0"]) {
        // 出发地址
        if ([self.type isEqualToString:@"0"])
        {
            //出发地 省
            userInfo[@"tag"] = @"101";
            
            NSDictionary *provience = [[[currentList objectAtIndex:indexPath.section] objectForKey:SectionValue] objectAtIndex:indexPath.row];
            userInfo[@"provienceName"] = [provience objectForKey:@"name"];
            userInfo[@"provienceCode"] = [provience objectForKey:@"code"];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"selectProvinceNotification" object:nil userInfo:userInfo];
            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            // ”市“
            NSDictionary *city = [[[currentList objectAtIndex:indexPath.section] objectForKey:SectionValue] objectAtIndex:indexPath.row];
            userInfo[@"tag"] = @"102";
            // 传“市”的信息
            userInfo[@"cityName"] = [city objectForKey:@"name"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"selectProvinceNotification" object:nil userInfo:userInfo];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else if ([self.from isEqualToString:@"1"]){
        // 目的地址
        if ([self.type isEqualToString:@"0"]) {
            // 目的地 省
            userInfo[@"tag"] = @"201";
            NSDictionary *provience = [[[currentList objectAtIndex:indexPath.section] objectForKey:SectionValue] objectAtIndex:indexPath.row];
            userInfo[@"provienceName"] = [provience objectForKey:@"name"];
            userInfo[@"provienceCode"] = [provience objectForKey:@"code"];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"selectProvinceNotification" object:nil userInfo:userInfo];
            [self.navigationController popViewControllerAnimated:YES];
        } else{
            // ”市“
            NSDictionary *city = [[[currentList objectAtIndex:indexPath.section] objectForKey:SectionValue] objectAtIndex:indexPath.row];
            userInfo[@"tag"] = @"202";
            // 传“市”的信息
            userInfo[@"cityName"] = [city objectForKey:@"name"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"selectProvinceNotification" object:nil userInfo:userInfo];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
   
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField.text isEqualToString:@"\n"])
    {
        [textField resignFirstResponder];
    }else
    {
      
       EreaListModel  *ereaModel = [EreaListModel sharedManager];
       searchArr =  [ereaModel getContentWithSearchStr:textField.text FromTableName:self.type];
        
        [self UpdateDataWithBuffer:searchArr];
       
        [textField resignFirstResponder];
    }
 
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    
    NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if ([toBeString length] == 0)
    {
        [searchArr removeAllObjects];
        [currentList removeAllObjects];
        [self UpdateDataWithBuffer:currentSourceData];
        
        
    }
    return YES;
}

- (void)searchWithContent:(UITextField *)textField
{
    NSLog(@"%@",searchText.text);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
